import {UserModel,sequelize} from '../until/context'
import {Op} from 'sequelize'
import User from "../model/user";

class UserService {
    async add(phone,username) {
        try {
            //@ts-ignore
             await UserModel.create({
                username,
                phone
            })
            return true
        } catch(err) {
            console.log(err)
            return false
        }
    }
    async remove(rid:number) {
        // 删除指定的用户
        let res = await UserModel.destroy({
            where: {
                rid
            }
        })
        return res
    }
    async find(phone,username) {
        // 查询指定的用户
            let res = await UserModel.findOne({
                where: {
                    [Op.or]: {
                        username,
                        phone
                    }
                }
            })
            return res
    }
    async update(rid,data) {
        // 修改指定用户的信息
       let result = await UserModel.update({
            ...data
        },{
            where: {
                rid
            }
        })
        return result
    }
    async findAll(pageSize,page,keyword) {
        // 查询所有用户
        let startPosition = (page - 1)*pageSize
        if (!keyword) {
            let obj = await UserModel.findAll({
                limit: pageSize,
                offset: startPosition
            })
            let total = await UserModel.count()
            return {total,data:obj}
        } else {
            console.log("模糊查询")
           let  { count, rows } = await UserModel.findAndCountAll({
                 where: {
                    [Op.or]: {
                        username: {
                            [Op.like]: '%' + keyword + '%'
                        },
                        phone: {
                            [Op.like]: '%' + keyword + '%'
                        }
                    }
                 },
                limit:pageSize,
                offset: startPosition
            })
            return {total:count,data:rows}
        }
    }
    async getUserAll() {
        // 获取用户的所有信息
        return await UserModel.findAll()
    }
}

export default new UserService()